import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  Select,
  Button,
  Table,
  message,
  DatePicker,
  TreeSelect,
  Modal,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import {
  text_check,
  post_axios,
  get_interval_date,
  add_zero,
  status_code_list,
  format_time,
} from "../../utils";
import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat";

export default function StatisticsMchSum(props) {
  dayjs.extend(customParseFormat);
  const { t } = useTranslation();
  const { RangePicker } = DatePicker;
  const [tableHeight, setTableHeight] = useState(0);
  const { actions, setSpinning } = props;
  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";
  let today_time = new Date();
  let year = today_time.getFullYear();
  let month = add_zero(today_time.getMonth() + 1);
  let day = add_zero(today_time.getDate());

  let last_time = new Date(get_interval_date(-7, "-"));
  let last_year = last_time.getFullYear();
  let last_month = add_zero(last_time.getMonth() + 1);
  let last_day = add_zero(last_time.getDate());

  const time_disabled = (current, partial, info) => {
    return current && current > dayjs().endOf("day");
  };

  const [com_ids_par, setCom_ids_par] = useState([]);
  const [mch_ids_par, setMch_ids_par] = useState([]);
  const [date_stamp, setDate_stamp] = useState([
    `${last_year}-${last_month}-${last_day}`,
    `${year}-${month}-${day}`,
  ]);
  const [tableList, setTableList] = useState([]);

  const getData = async (newPage, newRows) => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      bdate: date_stamp[0].replace(/-/g, ""),
      edate: date_stamp[1].replace(/-/g, ""),
      year: date_stamp[0].split("-")[0],
      com_ids_par: com_ids_par,
      mch_ids_par: mch_ids_par,
    };
    setSpinning(true);
    let res = await post_axios("statistics_mch_sum", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setTableList(res.data_rows.rows);
  };
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("transaction_flow.mch"),
      align: "center",
      dataIndex: "mch",
    },
    {
      title: t("transaction_flow.price"),
      align: "center",
      render: (_, record) => (
        <>
          <span>{record.price / 100}</span>
        </>
      ),
    },
    {
      title: t("transaction_flow.sales_volume"),
      dataIndex: "nu",
      align: "center",
    },
    {
      title: t("transaction_flow.price_dis_store"),
      align: "center",
      hidden: Boolean(session_company === "mg"),
      render: (_, record) => (
        <>
          <span>{record.price_dis_store / 100}</span>
        </>
      ),
    },
    {
      title: t("transaction_flow.price_dis_plate"),
      align: "center",
      render: (_, record) => (
        <>
          <span>{record.price_dis_plate / 100}</span>
        </>
      ),
    },
    {
      title: t("transaction_flow.price_dis_pay"),
      align: "center",
      render: (_, record) => (
        <>
          <span>{record.price_dis_pay / 100}</span>
        </>
      ),
    },
  ];

  const search_data = () => {
    initData(1);
  };

  const initData = (page, rows) => {
    getData();
  };

  // 获取组织列表
  const [com_list, setCom_list] = useState([]);
  const get_com_data = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      op_type: "list_com_id",
    };
    let res = await post_axios("admin_oneself", "m_query", upMsg);
    if (!res) return;
    setCom_list(res.data_rows.rows);
  };

  // 筛选_获取商户列表
  const [mch_page, setMch_page] = useState(1);
  const [mch_list, setMch_list] = useState([]);
  const get_mch_data = async (newPage) => {
    let upMsg = {
      page: newPage ? newPage : mch_page,
      rows: 20,
      company_id: local_company_object.id,
      company: local_company_object.company,
      op_type: "list_mch",
    };
    let res = await post_axios("admin_oneself", "m_query", upMsg);
    if (!res) return;
    const receiveRows = res.data_rows.rows;
    setMch_list([...mch_list, ...receiveRows]);
  };
  // 商户筛选框-分页
  const mch_next_page = () => {
    setMch_page(mch_page + 1);
    get_mch_data(mch_page + 1);
  };

  // 导出
  const [export_data_show, setExport_data_show] = useState(false);
  const [export_ranks_list, setExport_ranks_list] = useState([]);
  const export_data = async () => {
    await get_export_ranks_data();
    setExport_data_show(true);
  };
  const get_export_ranks_data = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      down_type: "statistics_mch_sum",
    };
    setSpinning(true);
    let res = await post_axios("task_export", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setExport_ranks_list(res.data_rows.rows);
  };

  const add_export_ranks = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      bdate: date_stamp[0].replace(/-/g, ""),
      edate: date_stamp[1].replace(/-/g, ""),
      year: date_stamp[0].split("-")[0],
      com_ids_par: com_ids_par,
      mch_ids_par: mch_ids_par,
    };
    setSpinning(true);
    let res = await post_axios("statistics_mch_sum", "m_export", upMsg);
    setSpinning(false);
    if (!res) return;
    get_export_ranks_data();
  };
  const download_export_data = (item) => {
    window.open(item.export_url);
  };
  const delete_export_data = async (item) => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      id: item.id,
      export_name: item.export_name,
    };
    setSpinning(true);
    let res = await post_axios("task_export", "m_del", upMsg);
    if (!res) return;
    setSpinning(false);
    message.warning({
      content: t("common.delete_success"),
    });
    get_export_ranks_data();
  };

  const exportRanksColumns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("operate.time"),
      align: "center",
      render: (_, record) => (
        <>{record.op_time ? format_time(record.op_time, "type_s") : ""}</>
      ),
    },
    {
      title: t("transaction_flow.file_name"),
      align: "center",
      width: 300,
      dataIndex: "export_name",
    },
    {
      title: t("transaction_flow.status"),
      align: "center",
      render: (_, record) => (
        <>{text_check(status_code_list[record.status_code])}</>
      ),
    },
    {
      title: t("transaction_flow.operation"),
      align: "center",
      render: (_, record) => (
        <>
          <Button
            size="small"
            type="primary"
            style={{
              marginRight: "10px",
            }}
            onClick={() => download_export_data(record)}
            disabled={record.status_code !== "Success"}
          >
            {t("transaction_flow.download")}
          </Button>
          <Button
            size="small"
            type="primary"
            danger
            onClick={() => delete_export_data(record)}
          >
            {t("transaction_flow.delete")}
          </Button>
        </>
      ),
    },
  ];

  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight =
        document.getElementsByClassName("statistics_mch_sum")[0].scrollHeight;
      const tableHeight = tabBoxHeight - 96 - 30;
      setTableHeight(tableHeight);
    });
    if (user_grade < 70) {
      get_com_data();
    }
    get_mch_data();
  }, []);
  return (
    <>
      <div className="statistics_mch_sum modules">
        <div className="screen_ipt">
          {user_grade < 70 ? (
            <div className="ipt_box ipt_box_long">
              <div className="ipt_box_title">{t("market.organization")}</div>
              <TreeSelect
                value={com_ids_par}
                treeData={com_list}
                allowClear={true}
                size="small"
                multiple
                treeCheckStrictly={true}
                fieldNames={{
                  label: "com",
                  value: "com_id",
                  children: "children",
                }}
                placeholder=" "
                treeCheckable={true}
                onChange={(newValue) => setCom_ids_par(newValue)}
              />
            </div>
          ) : (
            ""
          )}
          <div className="ipt_box ipt_box_long">
            <div className="ipt_box_title">{t("market.mch_name")}</div>
            <Select
              mode="multiple"
              size="small"
              placeholder=" "
              allowClear={true}
              value={mch_ids_par}
              options={mch_list}
              fieldNames={{
                label: "mch",
                value: "mch_id",
              }}
              onChange={(value) => setMch_ids_par(value)}
              onPopupScroll={(event) => {
                if (mch_list.length < mch_page * 20) {
                  console.log("没有更多商户的筛选数据了");
                  return;
                }
                const target = event.target;
                const residueHeight =
                  target.scrollHeight - target.scrollTop - target.clientHeight;
                if (residueHeight <= 50) {
                  mch_next_page();
                }
              }}
              optionFilterProp="mch"
            ></Select>
          </div>

          <div className="ipt_box ipt_box_long">
            <div className="ipt_box_title">{t("system_manager.time")}</div>
            <RangePicker
              // picker="month"
              disabledDate={time_disabled}
              size="small"
              onChange={(dates, dateStrings) => setDate_stamp(dateStrings)}
            />
          </div>
        </div>
        <div className="screen_btn">
          <div className="btn_box">
            {/* 添加 */}
            {menu_action.indexOf("m_add") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
              >
                {text_check(user_power_lang["m_add"])}
              </Button>
            ) : (
              ""
            )}
            {/* 修改 */}
            {menu_action.indexOf("m_modify") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<EditOutlined style={{ color: "#1677FF" }} />}
              >
                {text_check(user_power_lang["m_modify"])}
              </Button>
            ) : (
              ""
            )}
            {/* 删除 */}
            {menu_action.indexOf("m_del") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<DeleteOutlined style={{ color: "#1677FF" }} />}
              >
                {text_check(user_power_lang["m_del"])}
              </Button>
            ) : (
              ""
            )}

            {/* 导出 */}
            {menu_action.indexOf("m_export") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<DeleteOutlined style={{ color: "#1677FF" }} />}
                onClick={export_data}
              >
                {text_check(user_power_lang["m_export"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>
        <div className="table_box">
          <div
            className="noPage-table"
            style={{
              width: "100vw",
            }}
          >
            <Table
              dataSource={tableList}
              size="small"
              bordered
              columns={columns}
              rowKey="mch"
              virtual
              scroll={{
                y: tableHeight,
              }}
              rowHoverable={false}
              pagination={false}
            />
          </div>
        </div>
      </div>

      <Modal
        title={t("transaction_flow.export")}
        open={export_data_show}
        onOk={false}
        onCancel={() => setExport_data_show(false)}
        classNames={{ body: "edit_dialog_body", wrapper: "edit_900_style" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="export_btn">
          <div className="btn_box">
            {/* 添加 */}
            <Button
              size="small"
              type="text"
              icon={<PlusOutlined style={{ color: "#1677FF" }} />}
              onClick={add_export_ranks}
            >
              {text_check(user_power_lang["m_add"])}
            </Button>
            {/* 查询 */}
            <Button
              size="small"
              type="text"
              icon={<SearchOutlined style={{ color: "#1677FF" }} />}
              onClick={get_export_ranks_data}
            >
              {text_check(user_power_lang["m_query"])}
            </Button>
          </div>
        </div>

        <div className="noPage-table" style={{ height: "300px" }}>
          <Table
            dataSource={export_ranks_list}
            size="small"
            bordered
            columns={exportRanksColumns}
            rowKey="id"
            virtual
            scroll={{
              y: 300,
            }}
            rowHoverable={false}
            pagination={false}
          />
        </div>
      </Modal>
    </>
  );
}
